package com.service.impl;

import com.domain.Employee;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.EmployeeMapper;
import com.qo.QueryObject;
import com.service.EmployeeService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


@Transactional
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    @Override
    public void delete(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] roleIds) {
        //对密码进行加密(把用户名当做盐)
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());
        //保存之后employee就会有id
        mapper.insert(employee);
        //然后根据id插入
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                mapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return mapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] roleIds) {
        mapper.updateByPrimaryKey(employee);
        //删除关系
        mapper.deleteRelation(employee.getId());

        if (roleIds != null && roleIds.length > 0) {
            //关联关系
            for (Long roleId : roleIds) {
                mapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> list = mapper.selectLimitList(qo);
        return new PageInfo(list);
    }

    /*@Override
    public Employee login(String username, String password) {
        //判空
        //if (username == null || username.length() <= 0)
        if (!StringUtils.hasText(username)){  //org.springframework.util.StringUtils
            throw new LogicException("用户名不可为空");
        }
        if (!StringUtils.hasText(password)){
            throw new LogicException("密码不可为空");
        }
        //查询数据库中是否有匹配的数据
        Employee employee = mapper.selectByUsernameAndPassword(username, password);
        if(employee==null){
            //通知调用者出现异常
            throw new LogicException("账号和密码不匹配");
        }
        if(!employee.isStatus()){
            //通知调用者出现异常
            throw new LogicException("账号已被禁用");
        }
        return employee;
    }*/

    @Override
    public void updatePassword(Employee employee) {
        //对密码进行加密(把用户名当做盐)
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());
        mapper.updatePasswordById(employee);
    }

    @Override
    public void updateStatus(Employee employee) {
        mapper.updateStatusById(employee);
    }

    @Override
    public void batchDelete(Long[] ids) {
        mapper.batchDelete(ids);
        for (Long id : ids) {
            //删除关系
            mapper.deleteRelation(id);
        }
    }

    @Override
    public Employee selectByName(String name) {
        return mapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        //使用POI创建一个Excel
        Workbook wb = new HSSFWorkbook();
        //创建Excel中的sheet
        Sheet sheet1 = wb.createSheet("员工通讯录");
        //创建标题行数据，从0开始
        Row row = sheet1.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询所有员工
        List<Employee> list = mapper.selectAll();
        for (int i = 0; i < list.size(); i++) {
            Employee employee = list.get(i);
            //每个员工创建一行数据
            row = sheet1.createRow(i+1);
            //创建单元格，写入内容到单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail()==null ? "邮箱为空" : employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge()==null ? 0 : employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取上传的文件，并且封装为一个 Workbook
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引，说明一共有 lastRowNum+1 条数据
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i < lastRowNum+1; i++) {  //注意，标题行不读取
            //获取行数据
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            // 判断如果用户名是空，就不再往下读
            //一是解决用户名必填的问题
            //二是可以防止文件中间有空行的情况
            if(!StringUtils.hasLength(name.trim())){
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());
            //对于年龄，需要判断单元格数据类型
            Cell cell = row.getCell(2);
            if (cell.getCellType() == CellType.NUMERIC){  //如果填的是数字
                /*int age = (int) cell.getNumericCellValue();
                if (age < 18 || age>60){
                    throw new LogicException("第"+ i +"行数据有问题，年龄不在范围内");
                }*/
                employee.setAge((int) cell.getNumericCellValue());
            }else {   //作为文本类型单元格读取
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            }
            // 密码必填：设置默认密码 1
            employee.setPassword("1");
            //调用保存方法
            this.save(employee,null);
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String[] sns) {
        return mapper.selectByRoleSn(sns);
    }
}
